//
//  WXPContactChooseItemView.m
//  MexicoLoan
//
//  Created by wxp on 2025/3/3.
//

#import "WXPContactChooseItemView.h"
#import <ContactsUI/ContactsUI.h>

@interface WXPContactChooseItemView ()<CNContactPickerDelegate, UITextFieldDelegate>


@end

@implementation WXPContactChooseItemView

#pragma mark - lazy
- (UILabel *)labelTitle{
    if (_labelTitle == nil) {
        _labelTitle = [UILabel new];
        _labelTitle.textColor = COLOR_BLACK;
        _labelTitle.fontNum = 12;
        [_labelTitle fitTitle:@"Relación con Contact" variable:0];
    }
    return _labelTitle;
}
// 关系
- (UIView *)viewRelationBack{
    if (!_viewRelationBack) {
        _viewRelationBack = [UIView new];
        _viewRelationBack.widthHeight = XY(self.width-LEFT_MARDIN*2, Ratio(44));
        [GlobalMethod setRoundView:_viewRelationBack color:COLOR_LINE numRound:16 width:1];
        _viewRelationBack.tag = 1;
        UITapGestureRecognizer * tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick:)];
        [_viewRelationBack addGestureRecognizer:tapGestureRecognizer];
    }
    return _viewRelationBack;
}
- (UILabel *)labelRelationTitle{
    if (!_labelRelationTitle) {
        _labelRelationTitle = [UILabel new];
        _labelRelationTitle.fontNum = 14;
        _labelRelationTitle.textColor = COLOR_BLACK;
        [_labelRelationTitle fitTitle:@"Relación con el contacto" variable:0];
    }
    return _labelRelationTitle;
}
- (UITextField *)tfRelation{
    if (!_tfRelation) {
        _tfRelation = [UITextField new];
        _tfRelation.font = [UIFont boldSystemFontOfSize:14];
        _tfRelation.textColor = COLOR_BLACK;
        _tfRelation.textAlignment = NSTextAlignmentRight;
        _tfRelation.userInteractionEnabled = false;
    }
    return _tfRelation;
}
- (UIImageView *)imageArrow{
    if (!_imageArrow) {
        _imageArrow = [UIImageView new];
        _imageArrow.image = [UIImage imageNamed:@"icon-arrow-detail"];
        _imageArrow.widthHeight = XY(14, 14);
    }
    return _imageArrow;
}
// 名字
- (UIView *)viewNameBack{
    if (!_viewNameBack) {
        _viewNameBack = [UIView new];
        _viewNameBack.widthHeight = XY(self.width-LEFT_MARDIN*2, Ratio(44));
        [GlobalMethod setRoundView:_viewNameBack color:COLOR_LINE numRound:16 width:1];
        _viewNameBack.tag = 2;
        UITapGestureRecognizer * tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick:)];
        [_viewNameBack addGestureRecognizer:tapGestureRecognizer];
    }
    return _viewNameBack;
}
- (UILabel *)labelNameTitle{
    if (!_labelNameTitle) {
        _labelNameTitle = [UILabel new];
        _labelNameTitle.fontNum = 14;
        _labelNameTitle.textColor = COLOR_BLACK;
        [_labelNameTitle fitTitle:@"Nombre" variable:0];
    }
    return _labelNameTitle;
}
- (UITextField *)tfName{
    if (!_tfName) {
        _tfName = [UITextField new];
        _tfName.font = [UIFont boldSystemFontOfSize:14];
        _tfName.textColor = COLOR_BLACK;
        _tfName.textAlignment = NSTextAlignmentRight;
        [_tfName addTarget:self action:@selector(tfDidChange:) forControlEvents:(UIControlEventEditingChanged)];
        _tfName.delegate = self;
    }
    return _tfName;
}
- (UIImageView *)imageAddressBook
{
    if (_imageAddressBook == nil) {
        _imageAddressBook = [UIImageView  new];
        _imageAddressBook.widthHeight = XY(19, 20);
        _imageAddressBook.image = [UIImage imageNamed:@"icon-auth-address-book"];
    }
    return  _imageAddressBook;
}
// 手机号
- (UIView *)viewPhoneBack{
    if (!_viewPhoneBack) {
        _viewPhoneBack = [UIView new];
        _viewPhoneBack.widthHeight = XY(self.width-LEFT_MARDIN*2, Ratio(44));
        [GlobalMethod setRoundView:_viewPhoneBack color:COLOR_LINE numRound:16 width:1];
        _viewPhoneBack.tag = 3;
        UITapGestureRecognizer * tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick:)];
        [_viewPhoneBack addGestureRecognizer:tapGestureRecognizer];
    }
    return _viewPhoneBack;
}
- (UILabel *)labelPhoneTitle{
    if (!_labelPhoneTitle) {
        _labelPhoneTitle = [UILabel new];
        _labelPhoneTitle.fontNum = 14;
        _labelPhoneTitle.textColor = COLOR_BLACK;
        [_labelPhoneTitle fitTitle:@"Número de teléfono" variable:0];
    }
    return _labelPhoneTitle;
}
- (UITextField *)tfPhone{
    if (!_tfPhone) {
        _tfPhone = [UITextField new];
        _tfPhone.font = [UIFont boldSystemFontOfSize:14];
        _tfPhone.textColor = COLOR_BLACK;
        _tfPhone.keyboardType = UIKeyboardTypePhonePad;
        _tfPhone.textAlignment = NSTextAlignmentRight;
        _tfPhone.delegate = self;
        [_tfPhone addTarget:self action:@selector(tfDidChange:) forControlEvents:(UIControlEventEditingChanged)];
    }
    return _tfPhone;
}
- (WXPAuthPickerView *)pickerView{
    if (_pickerView == nil) {
        _pickerView = [WXPAuthPickerView  new];
        WEAKSELF
        _pickerView.blockDidSelectRow = ^(ModelBtn *model, NSInteger tag) {
            if (tag == 3){
                // 选择的联系人有多个手机号
                if (model != nil) {
                    weakSelf.tfPhone.text = model.title;
                    if(weakSelf.type == 1){
                        [GlobalMethod buryPointWithPageName:KEY_VerifyContact featureName:KEY_Contact_Phone_Input1 action:KEY_INPUT type:KEY_input];
                    }else{
                        [GlobalMethod buryPointWithPageName:KEY_VerifyContact featureName:KEY_Contact_Phone_Input2 action:KEY_INPUT type:KEY_input];
                    }
                    [weakSelf resetAuthBtnState];
                }
            }else{
                // 选择的关系
                if(tag == 1){
                    [GlobalMethod buryPointWithPageName:KEY_VerifyContact featureName:KEY_Contact_Relation1 action:KEY_LOST_FOCUS type:KEY_select];
                }else if(tag == 2){
                    [GlobalMethod buryPointWithPageName:KEY_VerifyContact featureName:KEY_Contact_Relation2 action:KEY_LOST_FOCUS type:KEY_select];
                }
                if(model != nil){
                    weakSelf.tfRelation.text = model.title;
                    weakSelf.relationship = model.content;
                }
            }
            [weakSelf resetAuthBtnState];
        };
    }
    return  _pickerView;
}

#pragma mark - 初始化
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        self.width = SCREEN_WIDTH-LEFT_MARDIN*2;
        [self configUI];
    }
    return self;
}

- (void)configUI{
    [self addSubview:self.labelTitle];
    
    [self addSubview:self.viewRelationBack];
    [self.viewRelationBack addSubview:self.labelRelationTitle];
    [self.viewRelationBack addSubview:self.imageArrow];
    [self.viewRelationBack addSubview:self.tfRelation];
    
    [self addSubview:self.viewNameBack];
    [self.viewNameBack addSubview:self.labelNameTitle];
    [self.viewNameBack addSubview:self.tfName];
    [self.viewNameBack addSubview:self.imageAddressBook];
    
    [self addSubview:self.viewPhoneBack];
    [self.viewPhoneBack addSubview:self.labelPhoneTitle];
    [self.viewPhoneBack addSubview:self.tfPhone];
    
    [self resetView];
}

#pragma mark - 手势点击
- (void)tapClick:(UITapGestureRecognizer * )tap{
    [NSObject clickFeedback];
    [tap.view addClickAnimate];
    UIWindow * window = [[[UIApplication sharedApplication] delegate] window];
    [window endEditing:true];
    if(tap.view.tag == 1){
        [self endEditing:true];
        if (self.type == 1){
            [GlobalMethod buryPointWithPageName:KEY_VerifyContact featureName:KEY_Contact_Relation1 action:KEY_GET_FOCUS type:KEY_select];
            [GlobalMethod hitPointWithPageName:KEY_VerifyContact action:KEY_Contact_Relation1_Focus extInfo:nil];
        }else{
            [GlobalMethod buryPointWithPageName:KEY_VerifyContact featureName:KEY_Contact_Relation2 action:KEY_GET_FOCUS type:KEY_select];
            [GlobalMethod hitPointWithPageName:KEY_VerifyContact action:KEY_Contact_Relation2_Focus extInfo:nil];
        }
        NSMutableArray * array = [NSMutableArray new];
        for (int i = 0; i < self.relationshipAry.count; i ++) {
            NSDictionary * dic = self.relationshipAry[i];
            ModelBtn * model = [ModelBtn new];
            model.title = [dic stringValueForKey:KEY_remark];
            model.content = [dic stringValueForKey:KEY_typeName];
            [array addObject:model];
        }
        [self.pickerView resetViewWithAry:array withTag:self.type];
        [window addSubview:self.pickerView];
    }
    if(tap.view.tag == 2){
        if (self.type == 1){
            [GlobalMethod buryPointWithPageName:KEY_VerifyContact featureName:KEY_Contact_Auto1 action:KEY_BUTTON_CLICK type:KEY_button];
            [GlobalMethod hitPointWithPageName:KEY_VerifyContact action:KEY_Contact1_Info_Focus extInfo:nil];
        }else{
            [GlobalMethod buryPointWithPageName:KEY_VerifyContact featureName:KEY_Contact_Auto2 action:KEY_BUTTON_CLICK type:KEY_button];
            [GlobalMethod hitPointWithPageName:KEY_VerifyContact action:KEY_Contact2_Info_Focus extInfo:nil];
        }
        WEAKSELF
        [GlobalMethod mainQueueBlock:^{
            CNContactPickerViewController *picker = [[CNContactPickerViewController alloc] init];
            picker.delegate = weakSelf;
            [Global_Nav presentViewController:picker animated:YES completion:nil];
        }];
    }
    if(tap.view.tag == 3){
        [self.tfPhone becomeFirstResponder];
    }
}

// 重置按钮状态
- (void)resetAuthBtnState{
    if(self.blockResetAuthBtnState){
        self.blockResetAuthBtnState();
    }
}

- (void)tfDidChange:(UITextField *)textField{
    [self resetAuthBtnState];
}

// 获得焦点
- (void)textFieldDidBeginEditing:(UITextField *)textField{
    if (self.type == 1){
        [GlobalMethod hitPointWithPageName:KEY_VerifyContact action:KEY_Contact1_Info_Focus extInfo:nil];
    }else{
        [GlobalMethod hitPointWithPageName:KEY_VerifyContact action:KEY_Contact2_Info_Focus extInfo:nil];
    }
    if(textField == self.tfName){
        if(self.type == 1){
            [GlobalMethod buryPointWithPageName:KEY_VerifyContact featureName:KEY_Contact_Name_Input1 action:KEY_GET_FOCUS type:KEY_input];
        }else{
            [GlobalMethod buryPointWithPageName:KEY_VerifyContact featureName:KEY_Contact_Name_Input2 action:KEY_GET_FOCUS type:KEY_input];
        }
    }
    if(textField == self.tfPhone){
        if(self.type == 1){
            [GlobalMethod buryPointWithPageName:KEY_VerifyContact featureName:KEY_Contact_Phone_Input1 action:KEY_GET_FOCUS type:KEY_input];
        }else{
            [GlobalMethod buryPointWithPageName:KEY_VerifyContact featureName:KEY_Contact_Phone_Input2 action:KEY_GET_FOCUS type:KEY_input];
        }
    }
}
// 失去焦点
- (void)textFieldDidEndEditing:(UITextField *)textField {
    if(textField == self.tfName){
        if(self.type == 1){
            [GlobalMethod buryPointWithPageName:KEY_VerifyContact featureName:KEY_Contact_Name_Input1 action:KEY_LOST_FOCUS type:KEY_input];
        }else{
            [GlobalMethod buryPointWithPageName:KEY_VerifyContact featureName:KEY_Contact_Name_Input2 action:KEY_LOST_FOCUS type:KEY_input];
        }
    }
    if(textField == self.tfPhone){
        if(self.type == 1){
            [GlobalMethod buryPointWithPageName:KEY_VerifyContact featureName:KEY_Contact_Phone_Input1 action:KEY_LOST_FOCUS type:KEY_input];
        }else{
            [GlobalMethod buryPointWithPageName:KEY_VerifyContact featureName:KEY_Contact_Phone_Input2 action:KEY_LOST_FOCUS type:KEY_input];
        }
    }
}
// 粘贴行为
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if(textField == self.tfName){
        if (isStr(string)){
            // 排除删除的情况（删除不打 input 点）
            if(self.type == 1){
                [GlobalMethod buryPointWithPageName:KEY_VerifyContact featureName:KEY_Contact_Name_Input1 action:KEY_INPUT type:KEY_input];
            }else{
                [GlobalMethod buryPointWithPageName:KEY_VerifyContact featureName:KEY_Contact_Name_Input2 action:KEY_INPUT type:KEY_input];
            }
        }
    }
    if(textField == self.tfPhone){
        if(isStr(string)){
            if(self.type == 1){
                [GlobalMethod buryPointWithPageName:KEY_VerifyContact featureName:KEY_Contact_Phone_Input1 action:KEY_INPUT type:KEY_input];
            }else{
                [GlobalMethod buryPointWithPageName:KEY_VerifyContact featureName:KEY_Contact_Phone_Input2 action:KEY_INPUT type:KEY_input];
            }
        }
    }
    // 检测是否为粘贴行为
    NSString * trimmedString = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if ([UIPasteboard generalPasteboard].string.length > 0 && [trimmedString isEqualToString:[UIPasteboard generalPasteboard].string]) {
        if(textField == self.tfName){
            if(self.type == 1){
                [GlobalMethod buryPointWithPageName:KEY_VerifyContact featureName:KEY_Contact_Name_Input1 action:KEY_PARSE type:KEY_input];
            }else{
                [GlobalMethod buryPointWithPageName:KEY_VerifyContact featureName:KEY_Contact_Name_Input2 action:KEY_PARSE type:KEY_input];
            }
        }
        if(textField == self.tfPhone){
            if(self.type == 1){
                [GlobalMethod buryPointWithPageName:KEY_VerifyContact featureName:KEY_Contact_Phone_Input1 action:KEY_PARSE type:KEY_input];
            }else{
                [GlobalMethod buryPointWithPageName:KEY_VerifyContact featureName:KEY_Contact_Phone_Input2 action:KEY_PARSE type:KEY_input];
            }
        }
        return true;
    }
    return YES;
}

#pragma mark - 选择联系人回调
- (void)contactPicker:(CNContactPickerViewController *)picker didSelectContact:(CNContact *)contact {
    // 获取联系人姓名
    NSString *givenName = contact.givenName;
    NSString *familyName = contact.familyName;
    // 全名
    NSString *fullName = [NSString stringWithFormat:@"%@%@%@", givenName, (isStr(givenName)&&isStr(familyName))?@" ":@"",familyName];
    self.tfName.text = fullName;
    self.tfPhone.text = @"";
    if(isStr(fullName)){
        if (self.type == 1){
            [GlobalMethod buryPointWithPageName:KEY_VerifyContact featureName:KEY_Contact_Name_Input1 action:KEY_INPUT type:KEY_input];
        }else{
            [GlobalMethod buryPointWithPageName:KEY_VerifyContact featureName:KEY_Contact_Name_Input2 action:KEY_INPUT type:KEY_input];
        }
    }
    
    // 获取联系人电话号码
    NSMutableArray * phoneArray = [NSMutableArray new];
    NSArray *phoneNumbers = contact.phoneNumbers;
    for (CNLabeledValue * phoneNumber in phoneNumbers) {
        CNPhoneNumber * number = phoneNumber.value;
        NSString * phoneNumberString = number.stringValue;
        
        ModelBtn * model = [ModelBtn new];
        model.title = phoneNumberString;
        model.content = phoneNumberString;
        [phoneArray addObject:model];
        
        NSLog(@"电话: %@", phoneNumberString);
    }
    // 有数据才弹窗
    if(isAry(phoneArray)){
        if (phoneArray.count > 1){
            // 联系人有多个联系方式，弹窗选择
            [self.pickerView resetViewWithAry:phoneArray withTag:3];
            UIWindow * window = [[[UIApplication sharedApplication] delegate] window];
            [window addSubview:self.pickerView];
        }else{
            // 联系人只有一个联系方式，直接填充该联系方式，不需要选了
            ModelBtn * model = phoneArray.firstObject;
            self.tfPhone.text = model.title;
            if (self.type == 1){
                [GlobalMethod buryPointWithPageName:KEY_VerifyContact featureName:KEY_Contact_Phone_Input1 action:KEY_INPUT type:KEY_input];
            }else{
                [GlobalMethod buryPointWithPageName:KEY_VerifyContact featureName:KEY_Contact_Phone_Input2 action:KEY_INPUT type:KEY_input];
            }
            [self resetAuthBtnState];
        }
    }
    
    // 使用获取到的数据
    // NSLog(@"姓名: %@", fullName);
    
    // 处理完毕后关闭通讯录控制器
    [picker dismissViewControllerAnimated:YES completion:nil];
}
 
- (void)contactPickerDidCancel:(CNContactPickerViewController *)picker {
    // 用户取消选择时的处理
    [picker dismissViewControllerAnimated:YES completion:nil];
}



#pragma mark - 刷新view
- (void)resetView{
    self.labelTitle.leftTop = XY(LEFT_MARDIN, Ratio(20));
    
    // 关系
    self.viewRelationBack.centerXTop = XY(self.width/2, self.labelTitle.bottom+Ratio(16));
    self.labelRelationTitle.leftCenterY = XY(LEFT_MARDIN, self.viewRelationBack.height/2);
    self.imageArrow.rightCenterY = XY(self.viewRelationBack.width-self.labelRelationTitle.left, self.viewRelationBack.height/2);
    self.tfRelation.widthHeight = XY(self.imageArrow.left-9-self.labelRelationTitle.right-9, self.viewRelationBack.height-10);
    self.tfRelation.rightCenterY = XY(self.imageArrow.left-9, self.viewRelationBack.height/2);
    
    // 名字
    self.viewNameBack.centerXTop = XY(self.width/2, self.viewRelationBack.bottom+Ratio(10));
    self.labelNameTitle.leftCenterY = XY(LEFT_MARDIN, self.viewNameBack.height/2);
    self.tfName.widthHeight = XY(self.tfRelation.right-self.labelNameTitle.right-9, self.viewNameBack.height-10);
    self.tfName.rightCenterY = XY(self.tfRelation.right, self.viewNameBack.height/2);
    self.imageAddressBook.centerXCenterY = XY(self.imageArrow.centerX, self.viewNameBack.height/2);
    
    // 电话
    self.viewPhoneBack.centerXTop = XY(self.width/2, self.viewNameBack.bottom+Ratio(10));
    self.labelPhoneTitle.leftCenterY = XY(LEFT_MARDIN, self.viewPhoneBack.height/2);
    self.tfPhone.widthHeight = XY(self.tfRelation.right-self.labelPhoneTitle.right-9, self.viewPhoneBack.height-10);
    self.tfPhone.rightCenterY = XY(self.tfRelation.right, self.viewPhoneBack.height/2);
    
    self.height = self.viewPhoneBack.bottom+self.labelTitle.top;
    [GlobalMethod setRoundView:self color:[UIColor clearColor] numRound:16 width:0];
}

- (void)resetTitle:(NSString *)title{
    [self.labelTitle fitTitle:readStr(title) variable:0];
    self.labelTitle.leftCenterY = self.labelTitle.leftCenterY;
}

@end
